import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'

import ElementPlus from 'unplugin-element-plus/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import basicSsl from '@vitejs/plugin-basic-ssl'

//这个配置 为了在html中使用 环境变量
const getViteEnv = (mode, target) => {
  return loadEnv(mode, process.cwd())[target]
}

// https://vitejs.dev/config/
export default  ({ mode }) => defineConfig({
  plugins: [
    vue(),
    basicSsl(),
    createHtmlPlugin({
      inject: {
        data: {
          //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
          title: getViteEnv(mode, 'VITE_APP_TITLE'),
        },
      },
    }),
    ElementPlus({
      useSource: true,
    }),
    AutoImport({ 
      imports: ['vue', '@vueuse/core', 'vue-router', 'pinia'],
      // dts: "src/auto-import.d.ts", // 生成在src路径下名为auto-import.d.ts的声明文件
      resolvers: [ElementPlusResolver(), IconsResolver({ prefix: 'Icon' })],
    }),,
    Components({
      resolvers: [ElementPlusResolver(), IconsResolver({ enabledCollections: ['ep'] })],
    }),
    Icons({
      autoInstall: true,
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/element/index.scss" as *;`,
      },
    },
  },
  build: {
    minify: 'terser',
    target: ['edge90', 'chrome90', 'firefox90', 'safari15'],
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: {
        entryFileNames: 'js/[name]-[hash].js',
        chunkFileNames: 'js/[name]-[hash].js',
        assetFileNames(chunkInfo){
          if(chunkInfo.name.endsWith('.css')){
            return 'css/[name]-[hash].css'
          }
          if(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg'].some(extname => chunkInfo.name.endsWith(extname))) {
            return 'img/[name]-[hash][extname]'
          }
          return '[ext]/[name]-[hash][extname]'
        },
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString();
          }
        }
      },
    }
  },
  server: {
    https: false,
    host: '0.0.0.0',
    port: 80,
    proxy: {
      [getViteEnv(mode, 'VITE_APP_BASE_API')]: {
        target: 'http://localhost:8381', // 接口域名
        secure: false, // 如果是https接口
        changeOrigin: true, // 是否跨域
        rewrite: (path) => { // 需要rewrite的
          return path.replace(new RegExp(`^${getViteEnv(mode, 'VITE_APP_BASE_API')}`), '')
        },
      },
      [getViteEnv(mode, 'VITE_APP_WS_API')]: {
        target: 'ws://localhost:8381',
        ws: true,
        secure: false,
        changeOrigin: true,
        rewrite: (path) => {
          return path.replace(new RegExp(`^${getViteEnv(mode, 'VITE_APP_WS_API')}`), '')
        },
      },
      '/gateway': {
        target: 'http://localhost:8381',
        secure: false,
        changeOrigin: true,
        rewrite: (path) => {
          return path.replace(new RegExp(`^/gateway`), '')
        },
      },
    },
  }
})
